package com.situ.mall.controller;

import com.situ.mall.constant.RedisConstants;
import com.situ.mall.util.AliOSSUtil;
import com.situ.mall.util.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class UploadController {
    @Autowired
    private RedisTemplate redisTemplate;

    //MultipartFile file封装图片上传所有信息
    @RequestMapping("/upload")
    public Result upload(MultipartFile file) {
        // 553dd137eabe4f6a947bc8d8d92afa7f
        String uuid = UUID.randomUUID().toString().replace("-", "");
        // 1.png
        String filename = file.getOriginalFilename();
        String extension = filename.substring(filename.lastIndexOf("."));
        String newFileName = uuid + extension;
        //553dd137eabe4f6a947bc8d8d92afa7f.png
        //上传到本地
        /*String filePath = "D:\\mypic\\" + newFileName;
        try {
            file.transferTo(new File(filePath));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }*/
        //上传到阿里云
        String url = "";
        try {
            url = AliOSSUtil.uploadFile(newFileName, file.getInputStream());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        //将上传的图片保存到redis中
        redisTemplate.opsForSet().add(RedisConstants.UPLOAD_IMAGE, url);

        return Result.ok("上传成功", url);
    }

    public static void main(String[] args) {
        String uuid = UUID.randomUUID().toString();
        System.out.println(uuid);//6839e95d-c1d2-419c-89c1-064cb8d6a8b1
        System.out.println(uuid.replace("-", ""));
        //553dd137eabe4f6a947bc8d8d92afa7f
    }

}
